package com.work.demo_01.controller;

import com.github.pagehelper.PageInfo;
import com.work.demo_01.Exception.ServiceException;
import com.work.demo_01.entity.User;
import com.work.demo_01.service.UserService;
import com.work.demo_01.utils.JsonResult;
import com.work.demo_01.utils.VerCodeGenerateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.MailException;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.thymeleaf.util.DateUtils;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("user")
public class UserController extends BaseController{
//    创建线程池对象
    ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10);
    @Autowired
    private UserService userService;
//    导入邮件类
    @Autowired
    private JavaMailSenderImpl mailSender;

//    实现获取邮箱验证码的接口
    @RequestMapping("sendEmail")
    public JsonResult<String> sendEmail(String email, HttpSession session){
//        调用工具类，生成4位随机验证码
        String code = VerCodeGenerateUtil.getVerCode();
//        获取当前时间
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String strDate = sdf.format(now);
        Map<String,String> map = new HashMap<>();
        map.put("code",code);
        map.put("email",email);
        System.out.println(code);
        System.out.println(email);
//        保存邮箱和验证码在服务缓存session中
        session.setAttribute("verCode",map);
        Map<String,String> codeMap = (Map<String, String>) session.getAttribute("verCode");
//        创建计时线程池，到时间自动移除验证码
        try{
            scheduledExecutorService.schedule(new Thread(() ->{
                if (email.equals(codeMap.get("email"))){
                    session.removeAttribute("verCode");
                }
            }),5*60, TimeUnit.SECONDS);
        }catch (Exception e){
            e.printStackTrace();
        }
//        发送邮件
        MimeMessage mimeMessage = null;
        MimeMessageHelper helper = null;
        try{
//            发送复杂的邮件
            mimeMessage = mailSender.createMimeMessage();
//            组装
            helper = new MimeMessageHelper(mimeMessage,true);
//            邮件标题
            helper.setSubject("第三组项目账号激活验证码");
            helper.setText("<h3>\n" +
                            "\t<span style=\"font-size:16px;\">亲爱的用户：</span> \n" +
                            "</h3>\n" +
                            "<p>\n" +
                            "\t<span style=\"font-size:14px;\">&nbsp;&nbsp;&nbsp;&nbsp;</span><span style=\"font-size:14px;\">&nbsp; <span style=\"font-size:16px;\">&nbsp;&nbsp;您好！您正在进行邮箱验证，本次请求的验证码为：<span style=\"font-size:24px;color:#FFE500;\"> "+code+"</span>,本验证码5分钟内有效，请在5分钟内完成验证。（请勿泄露此验证码）如非本人操作，请忽略该邮件。(这是一封自动发送的邮件，请不要直接回复）</span></span>\n" +
                            "</p>\n" +
                            "<p style=\"text-align:right;\">\n" +
                            "\t<span style=\"background-color:#FFFFFF;font-size:16px;color:#000000;\"><span style=\"color:#000000;font-size:16px;background-color:#FFFFFF;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;background-color:#FFFFFF;\">第三组</span></span></span> \n" +
                            "</p>\n" +
                            "<p style=\"text-align:right;\">\n" +
                            "\t<span style=\"background-color:#FFFFFF;font-size:14px;\"><span style=\"color:#FF9900;font-size:18px;\"><span class=\"token string\" style=\"font-family:&quot;font-size:16px;color:#000000;line-height:normal !important;\"><span style=\"font-size:16px;color:#000000;background-color:#FFFFFF;\">"+strDate+"</span><span style=\"font-size:18px;color:#000000;background-color:#FFFFFF;\"></span></span></span></span> \n" +
                            "</p>",true);
//            收件人
            helper.setTo(email);
//            发送方
            helper.setFrom("3279451839@qq.com");
            try{
//                发送邮件
                mailSender.send(mimeMessage);
            }catch (MailException e){
//                邮箱是无效的，或者发送失败
                return new JsonResult<String>(Failed,"无效邮箱！请重新输入邮箱！");
            }
        } catch (MessagingException e) {
//            发送失败，服务器繁忙
            return new JsonResult<String>(Failed,"发送失败");
        }
//        发送验证码成功
        return new JsonResult<String>(OK,"发送成功");
    }

//    实现用户注册的接口
    @RequestMapping("register")
    public JsonResult<String> register(String username,String password,String verCode,String newEmail,HttpServletRequest httpServletRequest){
//        获取session缓存中的信息
        HttpSession session = httpServletRequest.getSession();
        Map<String,String> codeMap = (Map<String,String>)session.getAttribute("verCode");
        String code = null;
        String email = null;
        try{
            code = codeMap.get("code");
            email = codeMap.get("email");
        }catch (Exception e){
//            验证码过期，或未找到 ——验证码无效
            return new JsonResult<String>(Failed,"验证码无效!");
        }
//        验证码判断(验证码不一致或邮箱不一致)
        if (!verCode.toUpperCase().equals(code) || !newEmail.equals(email)){
            return new JsonResult<String>(Failed,"验证码错误或所填写邮箱与验证码不匹配!");
        }
//        查询是否有重复的用户名
        User result = userService.findByUsername(username);
        if (result != null){
            return new JsonResult<String>(Failed,"用户名已存在!请换个用户名注册!");
        }
//        检查密码格式，包含字母、数字、特殊字符，至少8位，最多16位
        String regEx = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[^a-zA-Z0-9])(.{8,16})$";
        Pattern passwordPattern = Pattern.compile(regEx);
        Matcher matcher = passwordPattern.matcher(password);
        if (!matcher.matches()){
            return new JsonResult<String>(Failed,"密码格式错误!请重新输入密码!");
        }
//        补全信息
        Date now = new Date();
        User user = new User();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String time = sdf.format(now);
        user.setUsername(username);
        user.setPassword(password);
        user.setEmail(email);
        user.setCreatedTime(time);
        user.setState("已激活");
        user.setIdentity("否");
        try{
            userService.register(user);
//            验证码使用完后将session删除
            session.removeAttribute("verCode");
            return new JsonResult<String>(OK,"注册成功!");
        }catch (Exception e){
            return new JsonResult<String>(Failed,"注册失败！请联系管理员！");
        }
    }

//    实现用户列表分页的接口
    @RequestMapping("splitUser")
    public JsonResult<PageInfo> splitUser(int pageNum){
        PageInfo pageInfo = userService.splitPage(pageNum,5);
        int pages = pageInfo.getPages();
        if (pageNum > pages){
            PageInfo MaxPageInfo = userService.splitPage(pages,5);
            return new JsonResult<PageInfo>(OK,MaxPageInfo);
        }else {
            return new JsonResult<PageInfo>(OK,pageInfo);
        }
    }

//    根据查询条件获取用户信息列表
    @RequestMapping("getUser")
    public JsonResult<List<User>> getUser(User user){
        List<User> result = userService.getUser(user);
//        如果没有符合符合筛选条件的用户数据
        if (result.size() == 0){
            return new JsonResult<List<User>>(Failed,result);
        }
        return new JsonResult<List<User>>(OK,result);
    }
}
